package com.ssyc.gsk_teacher_appraisal.fragment;

import android.graphics.Color;
import android.os.Bundle;
import android.text.SpannableStringBuilder;
import android.text.Spanned;
import android.text.TextPaint;
import android.text.TextUtils;
import android.text.method.LinkMovementMethod;
import android.text.style.ClickableSpan;
import android.text.style.ForegroundColorSpan;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.ssyc.common.bean.BusInfo;
import com.ssyc.common.manager.TDialogManager;
import com.ssyc.common.utils.SPUtil;
import com.ssyc.common.utils.UiUtils;
import com.ssyc.common.view.flowlayout.FlowLayout;
import com.ssyc.common.view.flowlayout.TagAdapter;
import com.ssyc.common.view.flowlayout.TagFlowLayout;
import com.ssyc.gsk_teacher_appraisal.R;
import com.ssyc.gsk_teacher_appraisal.base.BaseLazyFragment;
import com.ssyc.gsk_teacher_appraisal.bean.QuestionDetailsInfo;
import com.ssyc.gsk_teacher_appraisal.constant.TeacherAppKeys;
import com.timmy.tdialog.TDialog;
import com.timmy.tdialog.base.BindViewHolder;
import com.timmy.tdialog.listener.OnBindViewListener;
import com.timmy.tdialog.listener.OnViewClickListener;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 选词填空
 * Created by Administrator on 2018/9/3 0003.
 */

public class AppraisalChooseWordFillArticFragment extends BaseLazyFragment {

    //服务器返回的页面数据对象
    private QuestionDetailsInfo info;

    //题目类型
    private TextView tvType;

    //顶部展示供选择单词的流式布局
    private TagFlowLayout flowlayout;

    //顶部布局
    private LinearLayout llTop;

    //底部布局
    private LinearLayout llBottom;


    //题干
    private TextView tvQuestion;

    //作答布局
    private LinearLayout llZd;
    //展示作答的流式布局
    private TagFlowLayout flOwnLayout;

    //正确答案布局
    private LinearLayout llZqda;
    //展示正确答案的流式布局
    private TagFlowLayout flRightAnswerLayout;


    //全校正确率的布局
    private LinearLayout llQxzql;
    //全校正确率的流式布局
    private TagFlowLayout flPresentLayout;

    //解析
    private TextView tvParseAnswer;
    private LinearLayout llShowAnswer;

    //页面跳转过来的区分标识,有四种状态 1老师查看试卷,2老师预览试卷,3老师查看学生成绩,4学生进入答题
    private int autherType = -1;
    private LayoutInflater mInflater;


    //切割的正则表达式,以2个下划线开头并且以2个下划线结尾,中间可以是任意字母和数字不限制个数
    private String reg = "_{2,}[0-9a-zA-Z]+_{2,}";
    //使用正则表达式切割后的字符串集合
    private String[] sentences;
    //用于保存用户输入的内容,初始值为服务器返回的_____5个下划线
    private Map<Integer, String> inputContent;

    //默认的用于替换用户输入答案的值
    public static final String DEFAULTCONTENT = "_____";
    private List<String> rightAnswers;


    /**
     * 获取当前Fragment对象方法
     *
     * @return
     */
    public static final AppraisalChooseWordFillArticFragment newInstance(QuestionDetailsInfo info) {
        AppraisalChooseWordFillArticFragment appraisalChooseWordFillSentenceFragment = new AppraisalChooseWordFillArticFragment();
        Bundle bundle = new Bundle();
        bundle.putSerializable("data", info);
        appraisalChooseWordFillSentenceFragment.setArguments(bundle);
        return appraisalChooseWordFillSentenceFragment;
    }

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_teacher_class_choose_word_fill_artic;
    }


    @Override
    public void lazyInit(View view, Bundle savedInstanceState) {

        //初始化视图
        initView(view);

        //获取数据
        initIntent();

        //同步界面视图的显示与隐藏状态
        sycViewState();

        //设置顶部的供选择单词的数据
        initTopWords();

        //设置题干的数据
        initQuestionContent();

        //设置底部数据的方法
        initBottomData();
    }


    /**
     * 初始化视图
     *
     * @param view
     */
    public void initView(View view) {
        tvType = view.findViewById(R.id.tv_type);
        flowlayout = view.findViewById(R.id.flowlayout);
        tvQuestion = view.findViewById(R.id.tv_question);
        flOwnLayout = view.findViewById(R.id.fl_own_layout);
        llZd = view.findViewById(R.id.ll_zd);
        flRightAnswerLayout = view.findViewById(R.id.fl_right_answer_layout);
        llZqda = view.findViewById(R.id.ll_zqda);
        flPresentLayout = view.findViewById(R.id.fl_present_layout);
        llQxzql = view.findViewById(R.id.ll_qxzql);
        tvParseAnswer = view.findViewById(R.id.tv_parse_answer);
        llShowAnswer = view.findViewById(R.id.ll_show_answer);
        mInflater = LayoutInflater.from(getActivity());
        llTop = view.findViewById(R.id.ll_top);
        llBottom = view.findViewById(R.id.ll_bottom);
        llTop.setVisibility(View.VISIBLE);
        llBottom.setVisibility(View.VISIBLE);

    }

    /**
     * 获取传递的数据
     */
    private void initIntent() {
        autherType = SPUtil.getInt(getContext(), TeacherAppKeys.AUTHERTYPE);

        //获取服务器返回的页面对象
        info = (QuestionDetailsInfo) getArguments().getSerializable("data");

        if (null != info) {
            //设置题目类型
            tvType.setText(info.getTitle_type());
        }

    }


    /**
     * 根据教师端和学生端不同入口状态
     * 同步界面视图的显示与隐藏方法
     */
    private void sycViewState() {
        if (autherType == 1) {
            //老师查看试卷
            //作答不显示
            llZd.setVisibility(View.GONE);

        } else if (autherType == 2) {
            //老师预览试卷
            //作答不显示
            llZd.setVisibility(View.GONE);
            //全校正确率不显示
            llQxzql.setVisibility(View.GONE);

        } else if (autherType == 3) {
            //老师查看学生成绩
            //全校正确率不显示
            llQxzql.setVisibility(View.GONE);

        } else if (autherType == 4) {
            //学生进入答题
            llShowAnswer.setVisibility(View.GONE);
        }
    }


    /**
     * 设置顶部的供选择单词的数据
     */
    private void initTopWords() {

        if (info == null) {
            return;
        }
        //获取所有供选择单词的拼接字符串
        String remarks = info.getRemarks();

        //设置顶部的流式布局
        if (!TextUtils.isEmpty(remarks)) {
            String[] strings = remarks.split(TeacherAppKeys.ANALYSIS);
            List<String> showWords = Arrays.asList(strings);
            //设置流式布局的数据
            flowlayout.setAdapter(new TagAdapter<String>(showWords) {
                @Override
                public View getView(FlowLayout parent, int position, String s) {
                    TextView tv = (TextView) mInflater.inflate(R.layout.teacher_class_tv_article,
                            flowlayout, false);
                    tv.setText(s);
                    return tv;
                }
            });
        }
    }

    /**
     * 设置题干的数据
     */
    private void initQuestionContent() {

        if (autherType != 4) {
            //非学生做题的情况下,不需要处理文字的点击事件
            sycQuestionByTeacher();
        } else {
            //学生端进入时,处理文字的点击事件
            sycQuestionByStudent();
        }
    }

    /**
     * 老师端设置题干的方法
     * 不需要处理点击事件
     */
    private void sycQuestionByTeacher() {

        if (info == null) {
            return;
        }


        //组装正确答案的数组,服务器返回
        List<QuestionDetailsInfo.SubListBean> sub_list = info.getSub_list();

        List<String> answersList = new ArrayList<>();
        if (null != sub_list && sub_list.size() != 0) {

            for (int i = 0; i < sub_list.size(); i++) {
                if (TextUtils.isEmpty(sub_list.get(i).getStudent_option())) {
                    answersList.add("___");
                } else {
                    answersList.add(sub_list.get(i).getStudent_option());
                }
            }
        }

        String[] rightAnswers = new String[answersList.size()];
        answersList.toArray(rightAnswers);


        //题干内容,服务器返回
        String questionContent = info.getContent();

        //将服务器返回的题干使用正则表达式切割
        sentences = questionContent.split(reg);

        //创建序号的集合
        String[] indexNums = new String[rightAnswers.length];

        for (int i = 0; i < rightAnswers.length; i++) {
            indexNums[i] = (i + 1) + ".";
        }

        //拼接需要重新显示的字符串
        String content = "";
        if (sentences.length == rightAnswers.length) {
            //题干内容以__结尾,切割的数组长度和填空的位置一样
            for (int i = 0; i < sentences.length; i++) {
                content += sentences[i] + indexNums[i] + rightAnswers[i];
            }

        } else {
            //题干内容不以__结尾,切割的字符串数组长度比需要填空的位置多一个
            for (int i = 0; i <= sentences.length - 2; i++) {
                //sentences的是8,但是inputContent的长度是7
                content += sentences[i] + indexNums[i] + rightAnswers[i];
            }
            content += sentences[sentences.length - 1];
        }


        //计算文字变色和添加下划线
        SpannableStringBuilder stringBuilder = new SpannableStringBuilder(content);

        //sentences={"English words by reading them "," I perfer to "," English words "," by reading them"}
        //rightAnswers = {"aloud", "aloud", "aloud"}
        // indexNums = {"1.", "2.", "3."};

        //第0个位置  sentences[0].length
        //第1个位置  sentences[0].length+indexNums[0].length+rightAnswers[0]+sentences[1].length
        //第2个位置  sentences[0].length+indexNums[0].length+rightAnswers[0]+sentences[1].length+indexNums[1].length+rightAnswers[1].length+sentences[2].length

        for (int i = 0; i < indexNums.length; i++) {

            //序号需要变色的起始位置
            int start = 0;
            int end = 0;

            for (int j = 0; j <= i; j++) {
                start += sentences[j].length();
            }

            for (int k = 0; k <= i - 1; k++) {
                start += indexNums[k].length();
                start += rightAnswers[k].length();
            }

            end = start + indexNums[i].length();

            //设置变色
            stringBuilder.setSpan(new ForegroundColorSpan(Color.parseColor("#EC8628")), start, end, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);


            //需要添加下划线的起始位置
            int clickStart = 0;
            int clikcEnd = 0;

            // A={"English words "," by reading them I perfer to "," English words "," by reading them"}
            //B = {"aloud", "aloud", "aloud"}
            // C = {"1.", "2.", "3."};


            String rs = "A[0]C[0]B[0]A[1]C[1]B[1]A[2]C[2]B[2]by reading them";
            //第0个位置 A[0]+C[0]
            //第1个位置 A[0]+C[0]+B[0]+A[1]+C[1]
            //第2个位置 A[0]+C[0]+B[0]+A[1]+C[1]+B[1]+A[2]+C[2]

            for (int j = 0; j <= i; j++) {
                clickStart += sentences[j].length();
                clickStart += indexNums[j].length();
            }

            for (int k = 0; k <= i - 1; k++) {
                clickStart += rightAnswers[k].length();
            }

            clikcEnd = clickStart + rightAnswers[i].length();

            //设置下划线和点击变色的文字位置
            stringBuilder.setSpan(new TextClick() {
                @Override
                public void onClick(View view) {
                }
            }, clickStart, clikcEnd, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);

        }

        //设置文字
        tvQuestion.setText(stringBuilder);

        //设置该方法后,点击事件才能生效
//        tvQuestion.setMovementMethod(LinkMovementMethod.getInstance());
    }

    /**
     * 学生端设置题干的方法
     * 需要处理点击事件
     */
    private void sycQuestionByStudent() {

        if (info == null) {
            return;
        }

        //题干内容,服务器返回
        String questionContent = info.getContent();

        //将服务器返回的题干使用正则表达式切割
        sentences = questionContent.split(reg);

        //获取服务器返回的正确答案的集合,也就是对应的填空个数

        //组装正确答案的数组,服务器返回
        rightAnswers = new ArrayList<>();

        List<QuestionDetailsInfo.SubListBean> sub_list = info.getSub_list();

        if (null != sub_list && sub_list.size() != 0) {

            for (int i = 0; i < sub_list.size(); i++) {
                rightAnswers.add(sub_list.get(i).getOption());
            }
        }

        //初始化创建Map用以保存输入的内容,默认值是DEFAULTCONTENT
        inputContent = new HashMap<>();

        for (int i = 0; i < rightAnswers.size(); i++) {
            inputContent.put(i, DEFAULTCONTENT);
        }

        sycStudentQuestionState();
    }

    /**
     * 同步学生将进入时题干的方法
     */
    private void sycStudentQuestionState() {

        //创建序号的集合
        String[] indexNums = new String[rightAnswers.size()];

        for (int i = 0; i < rightAnswers.size(); i++) {
            indexNums[i] = (i + 1) + ".";
        }

        //拼接需要重新显示的字符串
        String content = "";
        if (sentences.length == rightAnswers.size()) {
            //题干内容以__结尾,切割的数组长度和填空的位置一样
            for (int i = 0; i < sentences.length; i++) {
                content += sentences[i] + indexNums[i] + inputContent.get(i);
            }

        } else {
            //题干内容不以__结尾,切割的字符串数组长度比需要填空的位置多一个
            for (int i = 0; i <= sentences.length - 2; i++) {
                //sentences的是8,但是inputContent的长度是7
                content += sentences[i] + indexNums[i] + inputContent.get(i);
            }
            content += sentences[sentences.length - 1];
        }


        //计算文字变色和添加下划线
        SpannableStringBuilder stringBuilder = new SpannableStringBuilder(content);

        //sentences={"English words by reading them "," I perfer to "," English words "," by reading them"}
        //rightAnswers = {"aloud", "aloud", "aloud"}
        // indexNums = {"1.", "2.", "3."};

        //第0个位置  sentences[0].length
        //第1个位置  sentences[0].length+indexNums[0].length+rightAnswers[0]+sentences[1].length
        //第2个位置  sentences[0].length+indexNums[0].length+rightAnswers[0]+sentences[1].length+indexNums[1].length+rightAnswers[1].length+sentences[2].length

        for (int i = 0; i < indexNums.length; i++) {

            //记录点击的文字位置
            int index = i;

            //序号需要变色的起始位置
            int start = 0;
            int end = 0;

            for (int j = 0; j <= i; j++) {
                start += sentences[j].length();
            }

            for (int k = 0; k <= i - 1; k++) {
                start += indexNums[k].length();
                start += inputContent.get(k).length();
            }

            end = start + indexNums[i].length();

            //设置变色
            stringBuilder.setSpan(new ForegroundColorSpan(Color.parseColor("#EC8628")), start, end, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);


            //需要添加下划线的起始位置
            int clickStart = 0;
            int clikcEnd = 0;

            // A={"English words "," by reading them I perfer to "," English words "," by reading them"}
            //B = {"aloud", "aloud", "aloud"}
            // C = {"1.", "2.", "3."};


            String rs = "A[0]C[0]B[0]A[1]C[1]B[1]A[2]C[2]B[2]by reading them";
            //第0个位置 A[0]+C[0]
            //第1个位置 A[0]+C[0]+B[0]+A[1]+C[1]
            //第2个位置 A[0]+C[0]+B[0]+A[1]+C[1]+B[1]+A[2]+C[2]

            for (int j = 0; j <= i; j++) {
                clickStart += sentences[j].length();
                clickStart += indexNums[j].length();
            }

            for (int k = 0; k <= i - 1; k++) {
                clickStart += inputContent.get(k).length();
            }

            clikcEnd = clickStart + inputContent.get(i).length();

            //设置下划线和点击变色的文字位置
            stringBuilder.setSpan(new TextClick() {
                @Override
                public void onClick(View view) {
                    showInputPop(index);
                }
            }, clickStart, clikcEnd, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);

        }

        //设置文字
        tvQuestion.setText(stringBuilder);

        //设置该方法后,点击事件才能生效
        tvQuestion.setMovementMethod(LinkMovementMethod.getInstance());
    }


    /**
     * 设置底部数据的方法
     */
    private void initBottomData() {

        if (llShowAnswer.getVisibility() == View.VISIBLE) {
            //非学生端进入时需要显示底部数据

            //设置作答
            if (llZd.getVisibility() == View.VISIBLE) {
                //作答需要显示时才设置作答内容
                List<String> ownAnswers = new ArrayList<>();

                for (int i = 0; i < info.getSub_list().size(); i++) {
                    if (!TextUtils.isEmpty(info.getSub_list().get(i).getStudent_option())) {
                        ownAnswers.add((i + 1) + "." + info.getSub_list().get(i).getStudent_option());
                    } else {
                        ownAnswers.add((i + 1) + "." + "未作答");
                    }

                }

                flOwnLayout.setAdapter(new TagAdapter<String>(ownAnswers) {
                    @Override
                    public View getView(FlowLayout parent, int position, String s) {
                        TextView tv = (TextView) mInflater.inflate(R.layout.teacher_class_tv_ownanswer,
                                flOwnLayout, false);
                        tv.setText(s);
                        return tv;
                    }
                });
            }

            //正确答案的流式布局的数据
            List<String> rightAnswers = new ArrayList<>();
            for (int i = 0; i < info.getSub_list().size(); i++) {
                if (!TextUtils.isEmpty(info.getSub_list().get(i).getOption())) {
                    rightAnswers.add((i + 1) + "." + info.getSub_list().get(i).getOption());
                } else {
                    rightAnswers.add((i + 1) + "." + "");
                }

            }

            flRightAnswerLayout.setAdapter(new TagAdapter<String>(rightAnswers) {
                @Override
                public View getView(FlowLayout parent, int position, String s) {
                    TextView tv = (TextView) mInflater.inflate(R.layout.teacher_class_tv_rightanswer,
                            flRightAnswerLayout, false);
                    tv.setText(s);
                    return tv;
                }
            });

            //设置解析的数据
            tvParseAnswer.setText(info.getAnalysis());

            //设置全校正确率流式布局的数据
            if (llQxzql.getVisibility() == View.VISIBLE) {
                //全校正确率需要显示时才设置
                List<String> presents = new ArrayList<>();
                for (int i = 0; i < info.getSub_list().size(); i++) {
                    presents.add((i + 1) + info.getSub_list().get(i).getYes_pro());
                }
                flPresentLayout.setAdapter(new TagAdapter<String>(presents) {
                    @Override
                    public View getView(FlowLayout parent, int position, String s) {
                        TextView tv = (TextView) mInflater.inflate(R.layout.teacher_class_tv_qxzql,
                                flPresentLayout, false);
                        tv.setText(s);
                        return tv;
                    }
                });

            }

        }
    }

    /**
     * 点击事件
     */
    private abstract class TextClick extends ClickableSpan {
        @Override
        public void updateDrawState(TextPaint ds) {
            ds.setUnderlineText(true);
            ds.setStrokeWidth(3);
            ds.setColor(Color.parseColor("#EC8628"));
        }
    }


    /**
     * 点击空格位置弹出输入框的方法
     *
     * @param index
     */
    private void showInputPop(int index) {
//        PopUpManager.showPop(getContext(), R.layout.teacher_app_pop_input_form_blank, 0.3f, getActivity(), new PopUpManager.onGetViewListener() {
//            @Override
//            public void getChildView(View view, int layoutResId) {
//                //取消
//                TextView tvCancel = view.findViewById(R.id.tv_cancel);
//                //保存
//                TextView tvOk = view.findViewById(R.id.tv_ok);
//
//                //提示
//                TextView tvMsg = view.findViewById(R.id.tv_pop_content);
//                tvMsg.setText("请输入第" + (index + 1) + "空答案");
//
//                //输入框
//                EditText etInput = view.findViewById(R.id.et_input);
//
//                tvCancel.setOnClickListener(new View.OnClickListener() {
//                    @Override
//                    public void onClick(View view) {
//                        //关闭弹框
//                        PopUpManager.dismiss();
//                    }
//                });
//
//                tvOk.setOnClickListener(new View.OnClickListener() {
//                    @Override
//                    public void onClick(View view) {
//                        //点击确定后的操作
//                        //第一步:获取输入框的文字,进行非空判断
//                        String content = etInput.getText().toString().trim();
//                        if (TextUtils.isEmpty(content)) {
//                            //没有输入单词
//                            UiUtils.Toast("您还没有输入单词", false);
//                            return;
//                        } else {
//                            //已经输入了单词
//                            //第二步:将输入的单词回显到点击的空格位置
//
//                            //将用于保存输入框的内容的集合中点击的位置的值进行同步
////                            if (content.length() >= 4) {
////                                inputContent.put(index, content);
////                            } else if (content.length() == 3) {
////                                inputContent.put(index, " " + content + " ");
////                            }
//
//                            inputContent.put(index, content);
//
//                            //再次设置点击事件
//                            sycStudentQuestionState();
//
//                            PopUpManager.dismiss();
//
//                            //通过EventBs将用户作答本小题的相关信息传递给TkMainActivity保存
//                            //currPos对应的每个大题的小题的位置
//                            int choosePos = index;
//                            //用户选的输入的单词
//                            String chooseAnswer = content;
//                            //是否如正确
//                            boolean chooseResult = false;
//                            if (content.equals(rightAnswers.get(index))) {
//                                //用户作答正确
//                                chooseResult = true;
//                            } else {
//                                //用户作答错误
//                                chooseResult = false;
//                            }
//                            BusInfo busInfo = new BusInfo();
//                            busInfo.tkMsg = TeacherAppKeys.TKMsg;
//                            busInfo.tkChoosePos = choosePos;
//                            busInfo.tkChooseAnswer = chooseAnswer;
//                            busInfo.tkChooseResult = chooseResult;
//                            EventBus.getDefault().post(busInfo);
//                        }
//                    }
//                });
//            }
//        });


        TDialogManager.show(getActivity().getSupportFragmentManager(), R.layout.teacher_app_pop_input_form_blank, 0.3f, new OnBindViewListener() {
            @Override
            public void bindView(BindViewHolder viewHolder) {
                viewHolder.setText(R.id.tv_pop_content, "请输入第" + (index + 1) + "空答案");
            }
        }, new OnViewClickListener() {
            @Override
            public void onViewClick(BindViewHolder viewHolder, View view, TDialog tDialog) {
                int id = view.getId();
                if (id == R.id.tv_cancel) {
                    TDialogManager.dismiss();
                } else if (id == R.id.tv_ok) {
                    EditText etInput = viewHolder.getView(R.id.et_input);
                    //第一步:获取输入框的文字,进行非空判断
                    String content = etInput.getText().toString().trim();
                    if (TextUtils.isEmpty(content)) {
                        //没有输入单词
                        UiUtils.Toast("您还没有输入单词", false);
                        return;
                    } else {
                        //已经输入了单词
                        //第二步:将输入的单词回显到点击的空格位置

                        //将用于保存输入框的内容的集合中点击的位置的值进行同步
                        inputContent.put(index, "  " + content + "  ");

                        //再次设置点击事件
                        sycStudentQuestionState();

                        //通过EventBs将用户作答本小题的相关信息传递给TkMainActivity保存
                        //currPos对应的每个大题的小题的位置
                        int choosePos = index;
                        //用户选的输入的单词
                        String chooseAnswer = content;
                        //是否如正确
                        boolean chooseResult = false;
                        if (content.equals(rightAnswers.get(index))) {
                            //用户作答正确
                            chooseResult = true;
                        } else {
                            //用户作答错误
                            chooseResult = false;
                        }
                        BusInfo busInfo = new BusInfo();
                        busInfo.tkMsg = TeacherAppKeys.TKMsg;
                        busInfo.tkChoosePos = choosePos;
                        busInfo.tkChooseAnswer = chooseAnswer;
                        busInfo.tkChooseResult = chooseResult;
                        EventBus.getDefault().post(busInfo);

                        //关闭对话框
                        TDialogManager.dismiss();
                    }

                }
            }
        }, R.id.tv_cancel, R.id.tv_ok);
    }

}

